package com.singfan.manage;

import com.qiniu.util.Auth;
import com.singfan.common.util.CheckUtil;
import com.singfan.common.util.EncryptionUtil;
import com.singfan.common.util.JsonUtil;
import com.singfan.common.util.StringUtil;
import com.singfan.core.dao.database.config.ConfigDataManager;
import com.singfan.core.dao.database.config.SingFanConfigDao;
import com.singfan.core.dao.database.model.*;
import com.singfan.core.dao.database.model.config.MasterShopConfig;
import com.singfan.core.dao.database.model.constant.BusinessStatusType;
import com.singfan.core.dao.database.model.constant.OrderStatusType;
import com.singfan.core.service.*;
import com.singfan.manage.vm.*;
import com.singfan.manage.vm.partial.IncomeItem;
import com.singfan.manage.vm.partial.OrderItem;
import com.singfan.manage.vm.partial.ShopListItem;
import com.singfan.manage.vm.partial.ShopNameItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Author: hansonghe
 * Date: 2015-10-12 16:24
 * Desc:
 */
@Controller
public class AdminController {
    @Autowired
    private IManagerService managerService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IBarberService barberService;
    @Autowired
    private IShopService shopService;

    @RequestMapping(value="/login", method= RequestMethod.GET)
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("login");
        return view;
    }

    @RequestMapping(value="/login/submit", method= RequestMethod.POST)
    public void loginSubmit(HttpServletRequest request, HttpServletResponse response) {
        LoginModel result = new LoginModel();
        String name = request.getParameter("adminName");
        String pwd = request.getParameter("adminPwd");
        if (!StringUtil.isNullOrEmpty(name) && !StringUtil.isNullOrEmpty(pwd)){
            Manager manager = managerService.findManager(name, pwd);
            if (manager != null){
                request.getSession().setAttribute("ADMIN_KEY", manager);
                result.setResult(true);
            }
            else {
                result.setResult(false);
                result.setErrorMsg("用户名或密码不正确！");
            }
        }
        else {
            result.setResult(false);
            result.setErrorMsg("用户名或密码不能为空！");
        }

        bean2Response(response, result);
    }

    @RequestMapping(value="/main", method= RequestMethod.GET)
    public ModelAndView main(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("main");
        return view;
    }

    @RequestMapping(value="/header", method= RequestMethod.GET)
    public ModelAndView header(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("header");
        return view;
    }

    @RequestMapping(value="/menu", method= RequestMethod.GET)
    public ModelAndView menu(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("menu");
        return view;
    }

    @RequestMapping(value="/body", method= RequestMethod.GET)
    public ModelAndView body(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("body");
        return view;
    }

    @RequestMapping(value="/footer", method= RequestMethod.GET)
    public ModelAndView home(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("footer");
        return view;
    }

    @RequestMapping(value="/customer", method= RequestMethod.GET)
    public ModelAndView customer(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("customer");
        return view;
    }

    @RequestMapping(value="/barber", method= RequestMethod.GET)
    public ModelAndView barber(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("barber");
        return view;
    }

    @RequestMapping(value="/coupon", method= RequestMethod.GET)
    public ModelAndView coupon(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("coupon");
        List<CouponRecord> couponRecordList = customerService.findAllCouponRecordList();
        List<CouponModel> couponModelList = new ArrayList<>(couponRecordList.size());
        long now = System.currentTimeMillis();
        for (CouponRecord couponRecord : couponRecordList){
            CouponModel couponModel = new CouponModel();
            couponModel.setCouponId(couponRecord.getId());
            couponModel.setAmount(couponRecord.getAmount() / 100);
            couponModel.setBeginTime(couponRecord.getBeginTime().toString().split(" ")[0]);
            couponModel.setEndTime(couponRecord.getExpiredTime().toString().split(" ")[0]);
            if (StringUtil.isNullOrEmpty(couponRecord.getShopMasterName())) {
                couponModel.setMasterShopName("全部");
            }
            else {
                couponModel.setMasterShopName(couponRecord.getShopMasterName());
            }
            if (StringUtil.isNullOrEmpty(couponRecord.getShopSlaveName())) {
                couponModel.setSlaveShopName("全部");
            }
            else {
                couponModel.setSlaveShopName(couponRecord.getShopSlaveName());
            }
            if (couponRecord.getPriceCondition() == 0){
                couponModel.setCondition("无条件");
            }
            else{
                couponModel.setCondition("满" + (couponRecord.getPriceCondition()/100) + "元可用");
            }
            if (couponRecord.getExpiredTime().getTime() < now){
                couponModel.setStatus("已过期");
            }
            else{
                couponModel.setStatus("可使用");
            }

            couponModelList.add(couponModel);
        }

        List<ShopNameItem> masterShopNameList = getMasterShopNameList();
        view.addObject("masterShopNameList", masterShopNameList);
        view.addObject("couponList", couponModelList);

        return view;
    }

    @RequestMapping(value="/income/platform", method= RequestMethod.GET)
    public ModelAndView incomePlatform(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("income-platform");
        return view;
    }

    @RequestMapping(value="/income/shop", method= RequestMethod.GET)
    public ModelAndView incomeShop(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("income-shop");
        List<ShopNameItem> masterShopNameList = getMasterShopNameList();
        view.addObject("masterShopNameList", masterShopNameList);
        return view;
    }

    @RequestMapping(value="/shop", method= RequestMethod.GET)
    public ModelAndView shop(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("shop");
        List<ShopNameItem> masterShopNameList = getMasterShopNameList();
        view.addObject("uploadToken", getUploadToken());
        view.addObject("masterShopNameList", masterShopNameList);
        return view;
    }

    @RequestMapping(value="/order", method= RequestMethod.GET)
    public ModelAndView order(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("order");
        return view;
    }

    @RequestMapping(value="/customer/search", method= RequestMethod.POST)
    public void customerSearch(HttpServletRequest request, HttpServletResponse response){
        CustomerSearchModel result = new CustomerSearchModel();
        String telNum = request.getParameter("telNum");
        if (StringUtil.isNullOrEmpty(telNum)){
            result.setResult(false);
            result.setErrorMsg("手机号不能为空！");
        }
        else {
            Customer customer = customerService.findCustomerByPhoneNumber(telNum);
            if (customer != null){
                result.setResult(true);
                result.setTelNum(telNum);
                result.setStatus(customer.getStatus());
            }
            else {
                result.setResult(false);
                result.setErrorMsg("此手机号不存在对用的用户！");
            }

        }

        bean2Response(response, result);
    }

    @RequestMapping(value="/customer/op", method= RequestMethod.POST)
    public void customerOp(HttpServletRequest request, HttpServletResponse response){
        CustomerOpModel result = new CustomerOpModel();
        String telNum = request.getParameter("telNum");
        boolean action = Boolean.parseBoolean(request.getParameter("action"));
        if (StringUtil.isNullOrEmpty(telNum)){
            result.setResult(false);
            result.setErrorMsg("手机号不能为空！");
        }
        else {
            Customer customer = customerService.findCustomerByPhoneNumber(telNum);
            if (customer != null){
                if (action){
                    customerService.updateCustomerStatus(customer.getId(), BusinessStatusType.FORBIDDEN);
                    customerService.deleteCustomerToken(customer.getId());
                }
                else {
                    customerService.updateCustomerStatus(customer.getId(), BusinessStatusType.VERIFY_PASSED);
                }

                result.setResult(true);
                result.setTelNum(telNum);
            }
            else {
                result.setResult(false);
                result.setErrorMsg("此手机号不存在对应的用户！");
            }
        }

        bean2Response(response, result);
    }

    @RequestMapping(value="/barber/search", method= RequestMethod.POST)
    public void barberSearch(HttpServletRequest request, HttpServletResponse response){
        BarberSearchModel result = new BarberSearchModel();
        String telNum = request.getParameter("telNum");
        if (StringUtil.isNullOrEmpty(telNum)){
            result.setResult(false);
            result.setErrorMsg("手机号不能为空！");
        }
        else {
            Barber barber = barberService.findBarber(telNum);
            if (barber != null){
                result.setResult(true);
                result.setTelNum(telNum);
                result.setRealName(barber.getRealName());
                result.setNickName(barber.getNickName());
                result.setShopName(barber.getMasterShopName() + " " + barber.getSlaveShopName());
                result.setStatus(barber.getStatus());
            }
            else {
                result.setResult(false);
                result.setErrorMsg("此手机号不存在对应的技师！");
            }
        }

        bean2Response(response, result);
    }

    @RequestMapping(value="/barber/op", method= RequestMethod.POST)
    public void barberOp(HttpServletRequest request, HttpServletResponse response){
        CustomerOpModel result = new CustomerOpModel();
        String telNum = request.getParameter("telNum");
        boolean action = Boolean.parseBoolean(request.getParameter("action"));
        if (StringUtil.isNullOrEmpty(telNum)){
            result.setResult(false);
            result.setErrorMsg("手机号不能为空！");
        }
        else {
            Barber barber = barberService.findBarber(telNum);
            if (barber != null){
                if (action){
                    barberService.updateBarberStatus(barber.getId(), BusinessStatusType.FORBIDDEN);
                    barberService.deleteBarberToken(barber.getId());
                    barberService.updateBarberHairstyleStatus(barber.getId(), BusinessStatusType.NOT_VERIFY);
                }
                else {
                    barberService.updateBarberStatus(barber.getId(), BusinessStatusType.NOT_VERIFY);
                }

                result.setResult(true);
                result.setTelNum(telNum);
            }
            else {
                result.setResult(false);
                result.setErrorMsg("此手机号不存在对用的用户！");
            }
        }

        bean2Response(response, result);
    }

    @RequestMapping(value="/order/list", method= RequestMethod.POST)
    public void orderList(HttpServletRequest request, HttpServletResponse response){
        OrderListModel result = new OrderListModel();
        String telNum = request.getParameter("telNum");
        if (StringUtil.isNullOrEmpty(telNum)){
            result.setResult(false);
            result.setErrorMsg("手机号不能为空！");
        }
        else {
            List<Orders> ordersList = orderService.findCustomerOrderList(telNum);
            if (!ordersList.isEmpty()){
                List<OrderItem> orderItemList = new ArrayList<>(ordersList.size());
                for (Orders orders : ordersList){
                    OrderItem orderItem = new OrderItem();
                    orderItem.setOrderId(orders.getId());
                    orderItem.setCustomerPhone(orders.getCustomerPhoneNumber());
                    orderItem.setOrderName(orders.getOrderName());
                    orderItem.setDayTime(orders.getAppointmentDay());
                    orderItem.setClockTime(orders.getAppointmentClock());
                    String[] shopNames = orders.getShopName().split(" ");
                    orderItem.setMasterShopName(shopNames[0]);
                    orderItem.setSlaveShopName(shopNames[1]);
                    orderItem.setBarberName(orders.getBarberName());
                    orderItem.setPrice(orders.getOriginalPrice());
                    orderItem.setStatus(orders.getStatus());

                    orderItemList.add(orderItem);
                }
                result = OrderListModel.orderItemList2OrderListModel(orderItemList);
                result.setResult(true);
            }
            else {
                result.setResult(false);
                result.setErrorMsg("此手机号没有订单！");
            }
        }

        bean2Response(response, result);
    }

    @RequestMapping(value="/order/detail", method= RequestMethod.POST)
    public void orderDetail(HttpServletRequest request, HttpServletResponse response){
        OrderDetailModel result = new OrderDetailModel();
        String orderIdStr = request.getParameter("orderId");
        if (StringUtil.isNullOrEmpty(orderIdStr) || !CheckUtil.isPositiveInteger(orderIdStr)){
            result.setResult(false);
            result.setErrorMsg("订单号格式不正确！");
        }
        else {
            long orderId = Long.parseLong(orderIdStr);
            Orders orders = orderService.findOrdersById(orderId);
            if (orders != null){
                result.setResult(true);

                result.setOrderId(String.valueOf(orders.getId()));
                result.setCustomerPhone(orders.getCustomerPhoneNumber());
                result.setOrderName(orders.getOrderName());
                String dayStr = String.valueOf(orders.getAppointmentDay());
                String day = dayStr.substring(0,4) + "-" + dayStr.substring(4,6) + "-" + dayStr.substring(6,8);
                String clockStr = String.valueOf(orders.getAppointmentClock());
                String clock = clockStr.substring(0, clockStr.length() - 2) + ":" + clockStr.substring(clockStr.length() - 2, clockStr.length());
                result.setAppointmentTime(day + " " + clock);
                String[] shopNames = orders.getShopName().split(" ");
                result.setMasterShopName(shopNames[0]);
                result.setSlaveShopName(shopNames[1]);
                result.setBarberName(orders.getBarberName());
                result.setPrice(orders.getOriginalPrice() / 100);
                result.setCoupon((orders.getOriginalPrice() - orders.getPrice()) / 100);
                result.setRealPrice(orders.getPrice() / 100);
                result.setCreateTime(orders.getCreateTime().toString());
            }
            else {
                result.setResult(false);
                result.setErrorMsg("此订单号没有对应的订单！");
            }
        }

        bean2Response(response, result);
    }

    @RequestMapping(value="/order/refund", method= RequestMethod.POST)
    public void orderRefund(HttpServletRequest request, HttpServletResponse response){
        OrderDetailModel result = new OrderDetailModel();
        String orderIdStr = request.getParameter("orderId");
        if (StringUtil.isNullOrEmpty(orderIdStr) || !CheckUtil.isPositiveInteger(orderIdStr)){
            result.setResult(false);
            result.setErrorMsg("订单号格式不正确！");
        }
        else {
            long orderId = Long.parseLong(orderIdStr);
            orderService.updateOrderStatus(orderId, OrderStatusType.REFUNDED);
            result.setResult(true);
        }

        bean2Response(response, result);
    }

    @RequestMapping(value="/coupon/add", method= RequestMethod.POST)
    public void couponAdd(HttpServletRequest request, HttpServletResponse response){
        CouponModel result = new CouponModel();
        String endDate = request.getParameter("endDate");
        String amount = request.getParameter("amount");
        String common = request.getParameter("common");
        String slaveShop = request.getParameter("slaveShop");
        String condition = request.getParameter("condition");

        boolean checkResult = true;
        if (!checkDayTime(endDate)){
            checkResult = false;
            result.setErrorMsg("到期时间格式不正确！");
        }
        else if(!CheckUtil.isPositiveInteger(amount)) {
            checkResult = false;
            result.setErrorMsg("优惠劵金额不正确！");
        }
        else if (!(CheckUtil.isPositiveInteger(condition) || "0".equals(condition))){
            checkResult = false;
            result.setErrorMsg("使用条件不正确！");
        }
        else if (!("true".equals(common) || CheckUtil.isPositiveInteger(slaveShop))){
            checkResult = false;
            result.setErrorMsg("是否通用条件不正确！");
        }
        if (checkResult){
            int endDateValue = Integer.parseInt(endDate);
            int amountValue = Integer.parseInt(amount) * 100;
            int conditionValue = Integer.parseInt(condition) * 100;

            CouponRecord couponRecord = new CouponRecord();
            couponRecord.setAmount(amountValue);
            couponRecord.setPriceCondition(conditionValue);
            if ("true".equals(common)){
                couponRecord.setShopId(0);
            }
            else{
                long shopId = Long.parseLong(slaveShop);
                if (shopId > 0){
                    couponRecord.setShopId(shopId);
                    Shop shop = shopService.findShop(shopId);
                    couponRecord.setShopMasterName(shop.getMasterShopName());
                    couponRecord.setShopSlaveName(shop.getSlaveShopName());
                }
            }
            couponRecord.setBeginTime(new Date());
            couponRecord.setExpiredTime(int2Date(endDateValue));

            customerService.createCoupon(couponRecord);

            result.setCouponId(couponRecord.getId());
            result.setAmount(couponRecord.getAmount() / 100);
            result.setBeginTime(formatDate(couponRecord.getBeginTime()));
            result.setEndTime(formatDate(couponRecord.getExpiredTime()));
            if (StringUtil.isNullOrEmpty(couponRecord.getShopMasterName())) {
                result.setMasterShopName("全部");
            }
            else {
                result.setMasterShopName(couponRecord.getShopMasterName());
            }
            if (StringUtil.isNullOrEmpty(couponRecord.getShopSlaveName())) {
                result.setSlaveShopName("全部");
            }
            else {
                result.setSlaveShopName(couponRecord.getShopSlaveName());
            }

            if (couponRecord.getPriceCondition() == 0){
                result.setCondition("无条件");
            }
            else{
                result.setCondition("满" + (couponRecord.getPriceCondition()/100) + "元可用");
            }
            if (couponRecord.getExpiredTime().getTime() < System.currentTimeMillis()){
                result.setStatus("已过期");
            }
            else{
                result.setStatus("可使用");
            }

            result.setResult(true);

        }

        bean2Response(response, result);
    }

    @RequestMapping(value="/coupon/delete", method= RequestMethod.POST)
    public void couponDelete(HttpServletRequest request, HttpServletResponse response){
        CouponDeleteModel result = new CouponDeleteModel();
        String couponId = request.getParameter("couponId");
        if (CheckUtil.isPositiveInteger(couponId)){
            customerService.deleteCoupon(Long.parseLong(couponId));
            result.setResult(true);
        }
        else {
            result.setResult(false);
            result.setErrorMsg("优惠劵id不正确！");
        }

        bean2Response(response, result);
    }

    @RequestMapping(value="/income/data", method= RequestMethod.POST)
    public void incomeData(HttpServletRequest request, HttpServletResponse response) {
        String monthText = request.getParameter("year") + request.getParameter("month");
        long shopId = Long.parseLong(request.getParameter("shopId"));
        int monthValue = Integer.parseInt(monthText);
        List<Orders> ordersList = orderService.findOneMonthOrdersList(monthValue, shopId);
        Map<Integer, IncomeItem> incomeItemMap = new TreeMap<>();
        for (Orders order : ordersList){
            int day = order.getArrivalTime().getDate();
            IncomeItem incomeItem = incomeItemMap.get(day);
            if (incomeItem == null){
                incomeItem = new IncomeItem();
                incomeItem.setDay(String.valueOf(day));
                incomeItemMap.put(day, incomeItem);
            }

            incomeItem.setPrice(incomeItem.getPrice() + order.getOriginalPrice());
            incomeItem.setRealPrice(incomeItem.getRealPrice() + order.getPrice());
            incomeItem.setCoupon(incomeItem.getPrice() - incomeItem.getRealPrice());
        }

        Set<Integer> keySet = incomeItemMap.keySet();
        List<IncomeItem> incomeItemList = new ArrayList<>();
        for (Integer day : keySet){
            incomeItemList.add(incomeItemMap.get(day));
        }

        IncomeModel result = IncomeModel.createWithIncomeItem(incomeItemList);
        result.setResult(true);

        bean2Response(response, result);
    }

    @RequestMapping(value="/shop/list", method= RequestMethod.POST)
    public void shopList(HttpServletRequest request, HttpServletResponse response){
        ShopListModel result = new ShopListModel();

        Integer masterShopId = Integer.parseInt(request.getParameter("masterShopId"));
        Long slaveShopId = Long.parseLong(request.getParameter("salveShopId"));
        List<Shop> shopList = null;
        if (slaveShopId > 0){
            Shop shop = shopService.findShop(slaveShopId);
            if (shop != null){
                shopList = new ArrayList<>();
                shopList.add(shop);
            }
        }
        else {
            shopList = shopService.findSlaveShopList(masterShopId);
        }

        if (shopList != null){
            List<ShopListItem> shopListItemList = new ArrayList<>(shopList.size());
            int index=1;
            for (Shop shop : shopList){
                ShopListItem shopListItem = new ShopListItem();
                shopListItem.setNum(index++);
                shopListItem.setShopId(shop.getId());
                shopListItem.setMasterName(shop.getMasterShopName());
                shopListItem.setSlaveName(shop.getSlaveShopName());
                shopListItem.setHonor(shop.getHonor() / 2);
                shopListItem.setStatus(shop.getStatus());

                shopListItemList.add(shopListItem);
            }

            result = ShopListModel.createWithItemList(shopListItemList);
            result.setResult(true);
        }
        else {
            result.setResult(false);
        }


        bean2Response(response, result);
    }

    @RequestMapping(value="/shop/detail", method= RequestMethod.POST)
    public void shopDetail(HttpServletRequest request, HttpServletResponse response){
        Long shopId = Long.parseLong(request.getParameter("shopId"));
        Shop shop = shopService.findShop(shopId);
        ShopModel result = new ShopModel();
        result.setResult(true);
        result.setId(String.valueOf(shop.getId()));
        result.setRegisterPhone(shop.getRegisterPhone());
        result.setMasterId(shop.getMasterShopId());
        result.setMasterShopName(shop.getMasterShopName());
        result.setSlaveShopName(shop.getSlaveShopName());
        result.setShopIconUrl(shop.getShopIconUrl());
        String[] imgArr = shop.getImgList().split(";");
        List<String> imgList = new ArrayList<>(8);
        for (int i=0; i<8;i++){
            if (i < imgArr.length){
                if (StringUtil.isNullOrEmpty(imgArr[i])){
                    imgList.add("");
                }
                else {
                    imgList.add(imgArr[i]);
                }
            }
            else {
                imgList.add("");
            }
        }
        result.setShopImgUrl1(imgList.get(0));
        result.setShopImgUrl2(imgList.get(1));
        result.setShopImgUrl3(imgList.get(2));
        result.setShopImgUrl4(imgList.get(3));
        result.setShopImgUrl5(imgList.get(4));
        result.setShopImgUrl6(imgList.get(5));
        result.setShopImgUrl7(imgList.get(6));
        result.setShopImgUrl8(imgList.get(7));
        result.setDescription(shop.getDescription());
        result.setAddress(shop.getAddress());
        result.setCityId(shop.getCityId());
        result.setDistrictId(shop.getDistrictId());
        result.setCircleId(shop.getBusinessCircleId());
        result.setLongitude(shop.getLongitude().toString());
        result.setLatitude(shop.getLatitude().toString());
        result.setHonor(shop.getHonor() / 2);
        result.setStatus(BusinessStatusType.getBusinessStatusTypeTest(shop.getStatus()));

        bean2Response(response, result);
    }

    @RequestMapping(value="/shop/add", method= RequestMethod.POST)
    public void shopAdd(HttpServletRequest request, HttpServletResponse response){
        ShopCreateModel result = new ShopCreateModel();

        int masterId = Integer.parseInt(request.getParameter("masterId"));
        String masterName = request.getParameter("masterName");
        String slaveName = request.getParameter("slaveName");
        String desc = request.getParameter("desc");
        int star = Integer.parseInt(request.getParameter("selStar"));
        int cityId = Integer.parseInt(request.getParameter("cityId"));
        int districtId = Integer.parseInt(request.getParameter("districtId"));
        int circleId = Integer.parseInt(request.getParameter("circleId"));
        String shopIcon = request.getParameter("shopIcon");
        String shopImgList = request.getParameter("shopImgs");
        String address = request.getParameter("address");
        String lo = request.getParameter("lo");
        String la = request.getParameter("la");
        String phone = request.getParameter("phone");
        String pwd = request.getParameter("pwd");

        boolean checkResult = true;
        if (masterId > 0 && !StringUtil.isNullOrEmpty(masterName)){
            checkResult = false;
            result.setErrorMsg("你到底是要选择现有品牌还是要创建新的啊？！");
        }
        else if(masterId == 0 && StringUtil.isNullOrEmpty(masterName)){
            checkResult = false;
            result.setErrorMsg("请选择品牌！");
        }
        else if(masterId == 0 && !StringUtil.isNullOrEmpty(masterName) && masterName.length() > 64){
            checkResult = false;
            result.setErrorMsg("品牌名称过长！");
        }
        else if(StringUtil.isNullOrEmpty(slaveName) || slaveName.length() > 64){
            checkResult = false;
            result.setErrorMsg("分店名称不正确！");
        }
        else if(StringUtil.isNullOrEmpty(desc) || desc.length() > 500){
            checkResult = false;
            result.setErrorMsg("门店描述不正确！");
        }
        else if(StringUtil.isNullOrEmpty(address) || address.length() > 64){
            checkResult = false;
            result.setErrorMsg("分店地址不正确！");
        }
        else if ("/resource/img/shop_temp.png".equals(shopIcon)){
            checkResult = false;
            result.setErrorMsg("请选择门店头像！");
        }
        else if (StringUtil.isNullOrEmpty(shopImgList)){
            checkResult = false;
            result.setErrorMsg("请上传门店效果图！");
        }
        else if (StringUtil.isNullOrEmpty(phone)){
            checkResult = false;
            result.setErrorMsg("请填写门店电话！");
        }
        else if (StringUtil.isNullOrEmpty(pwd)){
            checkResult = false;
            result.setErrorMsg("请填写门店密码！");
        }

        try {
            BigDecimal longitude = new BigDecimal(lo);
            BigDecimal latitude = new BigDecimal(la);
            if (longitude.doubleValue() < 0 || longitude.doubleValue() > 180 || latitude.doubleValue() < 0 || latitude.doubleValue() > 180){
                checkResult = false;
                result.setErrorMsg("经纬度范围不正确！");
            }

            if (checkResult){
                result.setResult(true);
                if (masterId > 0){
                    boolean exist = shopService.isExistShopByName(masterId, slaveName);
                    if (exist){
                        result.setResult(false);
                        result.setErrorMsg("此分店已存在！");
                    }
                    else {
                        exist = shopService.isExistShopByPhone(phone);
                        if (exist){
                            result.setResult(false);
                            result.setErrorMsg("此分店已存在！");
                        }
                        else {
                            masterName = ConfigDataManager.getInstance().getMasterShopConfigMap(masterId).getName();
                        }
                    }
                }
                else {
                    boolean exist = false;
                    List<MasterShopConfig> masterShopConfigList = ConfigDataManager.getInstance().getMasterShopConfigList();
                    for (MasterShopConfig masterShopConfig : masterShopConfigList){
                        if (masterShopConfig.getName().equalsIgnoreCase(masterName)){
                            exist = true;
                            break;
                        }
                    }
                    if (exist){
                        result.setResult(false);
                        result.setErrorMsg("此品牌已存在！");
                    }
                    else {
                        masterId = SingFanConfigDao.getInstance().createMasterShop(masterName);
                        ConfigDataManager.getInstance().loadMasterShopConfig();
                        result.setReflush(true);
                    }

                }

                if (result.isResult()){
                    Shop shop = new Shop();
                    shop.setRegisterPhone(phone);
                    shop.setMasterShopId(masterId);
                    shop.setMasterShopName(masterName);
                    shop.setSlaveShopName(slaveName);
                    shop.setShopIconUrl(shopIcon);
                    shop.setImgList(shopImgList.substring(0, shopImgList.length()-1));
                    shop.setCompanyType(1);
                    shop.setDescription(desc);
                    shop.setAddress(address);
                    shop.setLongitude(longitude);
                    shop.setLatitude(latitude);
                    shop.setCityId(cityId);
                    shop.setDistrictId(districtId);
                    shop.setBusinessCircleId(circleId);
                    shop.setContactNumber(phone);
                    shop.setHonor(star);

                    Date now = new Date();
                    String passwordSalt = UUID.randomUUID().toString().substring(0, 7);
                    String password = EncryptionUtil.md5(pwd + "-" + passwordSalt);
                    shop.setPassword(password);
                    shop.setPasswordSalt(passwordSalt);
                    shop.setContactNumber(shop.getRegisterPhone());
                    shop.setStatus(BusinessStatusType.VERIFY_PASSED);
                    shop.setCreateTime(now);
                    shop.setUpdateTime(now);

                    shopService.createShop(shop);
                }
            }
            else {
                result.setResult(false);
            }
        }
        catch (Exception ex){
            ex.printStackTrace();
            result.setResult(false);
            result.setErrorMsg(ex.getMessage());
        }

        bean2Response(response, result);
    }

    @RequestMapping(value="/shop/update", method= RequestMethod.POST)
    public void shopUpdate(HttpServletRequest request, HttpServletResponse response){
        ShopUpdateModel result = new ShopUpdateModel();

        long shopId = Long.parseLong(request.getParameter("shopId"));
        int masterId = Integer.parseInt(request.getParameter("masterId"));
        String slaveName = request.getParameter("slaveName");
        String desc = request.getParameter("desc");
        int star = Integer.parseInt(request.getParameter("selStar"));
        int cityId = Integer.parseInt(request.getParameter("cityId"));
        int districtId = Integer.parseInt(request.getParameter("districtId"));
        int circleId = Integer.parseInt(request.getParameter("circleId"));
        String shopIcon = request.getParameter("shopIcon");
        String shopImgList = request.getParameter("shopImgs");
        String address = request.getParameter("address");
        String lo = request.getParameter("lo");
        String la = request.getParameter("la");

        boolean checkResult = true;
        if (masterId == 0){
            checkResult = false;
            result.setErrorMsg("请选择品牌！");
        }
        else if(StringUtil.isNullOrEmpty(slaveName) || slaveName.length() > 64){
            checkResult = false;
            result.setErrorMsg("分店名称不正确！");
        }
        else if(StringUtil.isNullOrEmpty(desc) || desc.length() > 64){
            checkResult = false;
            result.setErrorMsg("门店描述不正确！");
        }
        else if(StringUtil.isNullOrEmpty(address) || address.length() > 64){
            checkResult = false;
            result.setErrorMsg("分店地址不正确！");
        }
        else if ("/resource/img/shop_temp.png".equals(shopIcon)){
            checkResult = false;
            result.setErrorMsg("请选择门店头像！");
        }
        else if (StringUtil.isNullOrEmpty(shopImgList)){
            checkResult = false;
            result.setErrorMsg("请上传门店效果图！");
        }

        try {
            BigDecimal longitude = new BigDecimal(lo);
            BigDecimal latitude = new BigDecimal(la);
            if (longitude.doubleValue() < 0 || longitude.doubleValue() > 180 || latitude.doubleValue() < 0 || latitude.doubleValue() > 180){
                checkResult = false;
                result.setErrorMsg("经纬度范围不正确！");
            }

            if (checkResult){
                Date now = new Date();
                String masterName = ConfigDataManager.getInstance().getMasterShopConfigMap(masterId).getName();

                Shop shop = shopService.findShop(shopId);
                shop.setMasterShopId(masterId);
                shop.setMasterShopName(masterName);
                shop.setSlaveShopName(slaveName);
                shop.setShopIconUrl(shopIcon);
                shop.setImgList(shopImgList.substring(0, shopImgList.length()-1));
                shop.setCompanyType(1);
                shop.setDescription(desc);
                shop.setAddress(address);
                shop.setLongitude(longitude);
                shop.setLatitude(latitude);
                shop.setCityId(cityId);
                shop.setDistrictId(districtId);
                shop.setBusinessCircleId(circleId);
                shop.setHonor(star);
                shop.setContactNumber(shop.getRegisterPhone());
                shop.setUpdateTime(now);

                shopService.updateShopInfo(shop);

                result.setResult(true);
            }
            else {
                result.setResult(false);
            }
        }
        catch (Exception ex){
            result.setResult(false);
            result.setErrorMsg("经纬度格式不正确！");
        }

        bean2Response(response, result);
    }

    @RequestMapping(value="/shop/status", method= RequestMethod.POST)
    public void shopStatus(HttpServletRequest request, HttpServletResponse response){
        ShopStatusModel result = new ShopStatusModel();

        Long shopId = Long.parseLong(request.getParameter("shopId"));
        boolean forbid = Boolean.parseBoolean(request.getParameter("forbid"));
        shopService.forbidShop(shopId, forbid);
        result.setResult(true);

        bean2Response(response, result);
    }

    @RequestMapping(value="/shop/reset", method= RequestMethod.POST)
    public void shopReset(HttpServletRequest request, HttpServletResponse response){
        ShopStatusModel result = new ShopStatusModel();

        Long shopId = Long.parseLong(request.getParameter("shopId"));
        shopService.resetPwd(shopId);

        result.setResult(true);

        bean2Response(response, result);
    }

    @RequestMapping(value="/shop/name/list", method= RequestMethod.POST)
    public void shopNameList(HttpServletRequest request, HttpServletResponse response) {
        String shopId = request.getParameter("shopId");

        Integer masterShopId = Integer.parseInt(shopId);
        List<Shop> shopList = shopService.findSlaveShopList(masterShopId);
        List<ShopNameItem> shopNameItemList = new ArrayList<>(shopList.size());
        for (Shop shop : shopList){
            ShopNameItem shopNameItem = new ShopNameItem();
            shopNameItem.setId(String.valueOf(shop.getId()));
            shopNameItem.setName(shop.getSlaveShopName());
            shopNameItemList.add(shopNameItem);
        }

        ShopNameModel result = ShopNameModel.createWithShopNameItem(shopNameItemList);
        result.setResult(true);

        bean2Response(response, result);
    }

    private void bean2Response(HttpServletResponse response, Object responseModel){
        try {
            response.setContentType("text/json");
            response.setCharacterEncoding("UTF-8");
            String responseText = JsonUtil.bean2Json(responseModel);
            response.getWriter().write(responseText);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getUploadToken(){
        Auth auth = Auth.create("dpLrsXOAeQtki8qdgpC8ZiaDL3W3H3ZRLU2vkaV1", "zXsG2to1cP1gnlkUllJ6MP9965d1ecegGKZSm8sr");
        String uploadToken = auth.uploadToken("singfan-picture");
        return uploadToken;
    }

    private List<ShopNameItem> getMasterShopNameList(){
        List<MasterShopConfig> masterShopConfigList = ConfigDataManager.getInstance().getMasterShopConfigList();
        List<ShopNameItem> shopNameItemList = new ArrayList<>(masterShopConfigList.size());
        for (MasterShopConfig masterShopConfig : masterShopConfigList){
            ShopNameItem shopNameItem = new ShopNameItem();
            shopNameItem.setId(String.valueOf(masterShopConfig.getId()));
            shopNameItem.setName(masterShopConfig.getName());
            shopNameItemList.add(shopNameItem);
        }

        return shopNameItemList;
    }

    private Date int2Date(int dateValue){
        int year = dateValue / 10000;
        int month = ((dateValue % 10000) / 100) - 1;
        int day = dateValue % 100;
        return new Date(year - 1900, month, day);
    }

    private boolean checkDayTime(String dayTimeText){
        boolean result = false;
        if (CheckUtil.isPositiveInteger(dayTimeText)){
            int dayTime = Integer.parseInt(dayTimeText);
            if (dayTime > 20150831){
                long now = System.currentTimeMillis();
                int year = dayTime / 10000;
                int month = ((dayTime % 10000) / 100) - 1;
                int day = dayTime % 100;
                long appointmentTime = new Date(year, month, day).getTime();
                if (appointmentTime > now){
                    result = true;
                }
            }
        }

        return result;
    }

    private String formatDate(Date date){
        int year = date.getYear() + 1900;
        int month = date.getMonth() + 1;
        int day = date.getDate();
        return String.format("%1$d-%2$d-%3$d", year, month, day);
    }
}
